package com.braveman.im.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.braveman.im.R;
import com.braveman.im.bean.EditPersonInfoBean;
import com.braveman.im.bean.JsonNewBean;
import com.braveman.im.bean.PicUpdateBean;
import com.braveman.im.bean.UploadABusinessBean;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.thread.CompressPhotoThread;
import com.braveman.im.ui.weiget.ButtonItem;
import com.braveman.im.ui.weiget.CustomPopwindow;
import com.braveman.im.ui.weiget.DialogUtils;
import com.braveman.im.utils.GetJsonDataUtil;
import com.braveman.im.utils.PermissionUtils;
import com.braveman.im.utils.UtilsStyle;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ht.baselibs.core.EventCenter;
import com.ht.baselibs.core.EventCode;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.ui.widget.TitleBarView;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.UIUtils;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.vondear.rxtools.RxBarTool;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by 昊昊 on 2017/10/16.
 */

/**
 * 上传名片
 */
public class UploadABusinessCardActivity extends BaseActivity {

    private LinearLayout activityLayoutUploadHead;
    private QMUIRadiusImageView acticirtBtnItemImg;
    private EditText etActivityUploadName;
    private ButtonItem activityBtnItemSex;
    private EditText etActivityUploadPhone;
    private ButtonItem activityBtnItemHometown;
    private ButtonItem activityBtnItemLand;
    private EditText etActivityUploadSignature;
    private EditText etActivityUploadCompyName;
    private EditText etActivityUploadDuty;
    private EditText etActivityUploadCompyPhone;
    private ButtonItem etActivityUploadAdress;
    private EditText etActivityUploadPostcode;
    private TextView activityUploadOkBtn;
    private UploadABusinessBean uploadABusinessBean;
    private String[] Sex = {"男", "女", "保密"};
    private List<String> SexList = new ArrayList<>();
    private String sexName;
    private String hometownId;//故乡ID
    private String hometownName;//故乡名称
    private String residenceId;//常驻ID
    private String residenceName;//常驻地名称
    private String corpAddressId;//公司地址id
    private String corpAddressName;//公司地址名称
    private ArrayList<JsonNewBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>>> options3Items = new ArrayList<>();
    private Thread thread;
    private boolean isLoaded = false;
    private String picturePath;
    private String picturePathToURl;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final String TAKE_PHOTO_PATH = "ht/jkm/photo/HEADAV.jpg";
    private static final int REQUEST_CODE_TAKE_PHOTO = 1;
    private static final int REQUEST_CAMERA_CODE = 2;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 0;
    private static final int MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD = 1;
    private String url;

    @Override
    protected void initTitleBar() {
        mTitleBarView.setTitleText("上传名片").setLeftBtnIcon(R.mipmap.back_black).setOnLeftBtnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.finishActivity(UploadABusinessCardActivity.this);
            }
        });
    }

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected int initContentView() {
        UtilsStyle.setStatusBarMode(this, true);
        RxBarTool.FlymeSetStatusBarLightMode(getWindow(), true);
        RxBarTool.MIUISetStatusBarLightMode(getWindow(), true);
        return R.layout.activity_upload_a_business_card;
    }

    @Override
    protected void initChildView() {
        // activityLayoutUploadHead = (LinearLayout) findViewById(R.id.activity_layout_upload_head);
        acticirtBtnItemImg = findViewById(R.id.acticirt_btn_item_img);
        etActivityUploadName = findViewById(R.id.et_activity_upload_name);
        activityBtnItemSex = findViewById(R.id.activity_btn_item_sex);
        etActivityUploadPhone = findViewById(R.id.et_activity_upload_phone);
        activityBtnItemHometown = findViewById(R.id.activity_btn_item_hometown);
        activityBtnItemLand = (ButtonItem) findViewById(R.id.activity_btn_item_land);
        etActivityUploadSignature = (EditText) findViewById(R.id.et_activity_upload_signature);
        etActivityUploadCompyName = (EditText) findViewById(R.id.et_activity_upload_compy_name);
        etActivityUploadDuty = (EditText) findViewById(R.id.et_activity_upload_duty);
        etActivityUploadCompyPhone = (EditText) findViewById(R.id.et_activity_upload_compy_phone);
        etActivityUploadAdress = (ButtonItem) findViewById(R.id.et_activity_upload_adress);
        etActivityUploadPostcode = (EditText) findViewById(R.id.et_activity_upload_postcode);
        activityUploadOkBtn = (TextView) findViewById(R.id.activity_upload_ok_btn);
        acticirtBtnItemImg.setCircle(false);

    }

    @Override
    protected void initChildData() {
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);//故乡
        for (String sex : Sex) {//性别选择
            SexList.add(sex);
        }
    }

    // TODO: 2017/11/7 故乡城市选择器
    private void ShowPickerView(final ButtonItem buttonItem) {
        OptionsPickerView pickerView = new OptionsPickerView.Builder(UploadABusinessCardActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                hometownName = options3Items.get(options1).get(options2).get(options3).name;
                buttonItem.tv_des.setText(hometownName);
                hometownId = options3Items.get(options1).get(options2).get(options3).id;
            }
        }).setTitleText("故乡城市")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20).build();
        pickerView.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pickerView.show();
    }

    /**
     * 常驻地选择器
     *
     * @param buttonItem
     */
    private void ShowResidenceView(final ButtonItem buttonItem) {
        OptionsPickerView ResidenceView = new OptionsPickerView.Builder(UploadABusinessCardActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                residenceId = options3Items.get(options1).get(options2).get(options3).id;
                residenceName = options3Items.get(options1).get(options2).get(options3).name;
                buttonItem.tv_des.setText(residenceName);
            }
        }).setTitleText("常驻城市")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20).build();
        ResidenceView.setPicker(options1Items, options2Items, options3Items);//三级选择器
        ResidenceView.show();
    }

    /**
     * 公司地址
     *
     * @param buttonItem
     */
    private void ShowCompyView(final ButtonItem buttonItem) {
        OptionsPickerView CompyView = new OptionsPickerView.Builder(UploadABusinessCardActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                corpAddressId = options3Items.get(options1).get(options2).get(options3).id;
                corpAddressName = options3Items.get(options1).get(options2).get(options3).name;
                buttonItem.tv_des.setText(corpAddressName);
            }
        }).setTitleText("公司地址")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20).build();
        CompyView.setPicker(options1Items, options2Items, options3Items);//三级选择器
        CompyView.show();
    }

    // TODO: 2017/11/7 性别选择器
    private void ShowSexView(final ButtonItem buttonItem) {
        OptionsPickerView pickerView = new OptionsPickerView.Builder(UploadABusinessCardActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                sexName = SexList.get(options1);
                buttonItem.tv_des.setText(sexName);
            }
        }).setTitleText("选择性别")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20).build();
        pickerView.setPicker(SexList);
        pickerView.show();
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.activity_upload_ok_btn:
                uploadABusinessBean = new UploadABusinessBean();
                if (etActivityUploadName.getText().toString().trim().isEmpty() || etActivityUploadPhone.getText().toString().trim().isEmpty() || etActivityUploadSignature.getText().toString().trim().isEmpty() || etActivityUploadCompyName.getText().toString().isEmpty() || etActivityUploadDuty.getText().toString().trim().isEmpty() || etActivityUploadCompyPhone.getText().toString().trim().isEmpty() || etActivityUploadPostcode.getText().toString().trim().isEmpty()) {
                    Toast.makeText(this, "请完善您的记录", Toast.LENGTH_SHORT).show();
                } else {
                    Glide.with(UploadABusinessCardActivity.this).load(uploadABusinessBean.avatar).into(acticirtBtnItemImg);
                    uploadABusinessBean.name = etActivityUploadName.getText().toString().trim();
                    uploadABusinessBean.personalPhone = etActivityUploadPhone.getText().toString().trim();
                    uploadABusinessBean.information = etActivityUploadSignature.getText().toString().trim();
                    uploadABusinessBean.corpName = etActivityUploadCompyName.getText().toString().trim();
                    uploadABusinessBean.position = etActivityUploadDuty.getText().toString().trim();
                    uploadABusinessBean.businessPhone = etActivityUploadCompyPhone.getText().toString().trim();
                    //  uploadABusinessBean.corpDetailedAddress = etActivityUploadAdress.getText().toString().trim();
                    uploadABusinessBean.zipCode = etActivityUploadPostcode.getText().toString().trim();
                    uploadABusinessBean.gender = "男".equals(sexName) ? "1" : "2";
                    if (TextUtils.isEmpty(url)) {
                        UIUtils.showToast("请上传头像");
                        return;
                    }
                    if (TextUtils.isEmpty(hometownId)) {
                        UIUtils.showToast("请选择故乡");
                        return;
                    }
                    uploadABusinessBean.hometownId = hometownId;//故乡选择ID
                    if (TextUtils.isEmpty(residenceId)) {
                        UIUtils.showToast("请选择常驻地址");
                        return;
                    }
                    uploadABusinessBean.residenceId = residenceId;//常驻地ID
                    if (TextUtils.isEmpty(corpAddressId)) {
                        UIUtils.showToast("请选择公司地址");
                    }
                    uploadABusinessBean.corpAddressId = corpAddressId;//公司地址ID
                    uploadABusinessBean.avatar = url;//头像
                    ApiManager.getApi().getUpLoad(uploadABusinessBean).enqueue(new NetCallBack<UploadABusinessBean>() {
                        @Override
                        protected void onSuccess(Call<UploadABusinessBean> call, Response<UploadABusinessBean> response) {
                            uploadABusinessBean = response.body();
                            if (response != null) {
                                UIUtils.showToast("名片上传成功");
                                EventBus.getDefault().post(new EventCenter(EventCode.EVENT_UPLOAD_CARD_SUCESS));
                                ActivityUtils.finishActivity(UploadABusinessCardActivity.this);
                            }
                        }
                    });
                }
                break;
            case R.id.activity_btn_item_sex://性别选择
                ShowSexView(activityBtnItemSex);
                break;
            case R.id.activity_btn_item_hometown://故乡选择
                ShowPickerView(activityBtnItemHometown);
                break;
            case R.id.activity_btn_item_land://常驻地选择
                ShowResidenceView(activityBtnItemLand);
                break;
            case R.id.et_activity_upload_adress:
                ShowCompyView(etActivityUploadAdress);//公司地址选择
                break;
            case R.id.acticirt_btn_item_img://头像
                try {
                    InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }
                break;
        }
    }

    @Override
    protected void setChildViewListener() {
        //activityLayoutUploadHead.setOnClickListener(this);
        acticirtBtnItemImg.setOnClickListener(this);
        etActivityUploadName.setOnClickListener(this);
        activityBtnItemSex.setOnClickListener(this);
        etActivityUploadPhone.setOnClickListener(this);
        activityBtnItemHometown.setOnClickListener(this);
        activityBtnItemLand.setOnClickListener(this);
        etActivityUploadSignature.setOnClickListener(this);
        etActivityUploadCompyName.setOnClickListener(this);
        etActivityUploadDuty.setOnClickListener(this);
        etActivityUploadCompyPhone.setOnClickListener(this);
        etActivityUploadAdress.setOnClickListener(this);
        etActivityUploadPostcode.setOnClickListener(this);
        activityUploadOkBtn.setOnClickListener(this);
    }

    // TODO: 2017/11/7 解析省市区数据
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        Toast.makeText(UploadABusinessCardActivity.this, "Begin Parse Data", Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    Toast.makeText(UploadABusinessCardActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;
                case MSG_LOAD_FAILED:
                    Toast.makeText(UploadABusinessCardActivity.this, "Parse Failed", Toast.LENGTH_SHORT).show();
                    break;
                case 200: //图片
                    int type = (int) msg.obj;
                    switch (type) {
                        case 0:
                            picturePathToURl = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                            Glide.with(UploadABusinessCardActivity.this)//
                                    .load(Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH)//
                                    .into(acticirtBtnItemImg);
                            toUpdata(picturePathToURl);
                            break;
                        case 1:
                            picturePathToURl = picturePath;
                            Glide.with(UploadABusinessCardActivity.this)//
                                    .load(picturePath)
                                    .into(acticirtBtnItemImg);
                            toUpdata(picturePathToURl);
                            break;

                    }
                    break;
            }
        }
    };

    private void toUpdata(String path) {
        File file = new File(path);
        final RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        showLoadingDialog();
        ApiManager.getApi().uploadPic("image", filePart).enqueue(new NetCallBack<List<PicUpdateBean>>() {
            @Override
            protected void onSuccess(Call<List<PicUpdateBean>> call, Response<List<PicUpdateBean>> response) {
                UIUtils.showToast("图片上传成功");
                if (response != null) {
                    if (response.body().size() != 0) {
                        PicUpdateBean picUpdateBean = response.body().get(0);
                        url = picUpdateBean.url;

                    }

                }
            }

            @Override
            protected void hiddenProgress() {
                hideLodingDialog();
            }
        });
    }

    // TODO: 2017/11/7 Gson解析
    public ArrayList<JsonNewBean> parseData(String result) {  //Gson 解析
        ArrayList<JsonNewBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonNewBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonNewBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    // TODO: 2017/11/7 解析数据
    private void initJsonData() {   //解析数据
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(UploadABusinessCardActivity.this, "province_new.json");//获取assets目录下的json文件数据
        ArrayList<JsonNewBean> jsonBean = parseData(JsonData);//用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;
        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<JsonNewBean.ChildBeanX.ChildBean> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<JsonNewBean.ChildBeanX.ChildBean>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (int c = 0; c < jsonBean.get(i).child.size(); c++) {//遍历该省份的所有城市
                JsonNewBean.ChildBeanX.ChildBean childBean = new JsonNewBean.ChildBeanX.ChildBean();
                childBean.name = jsonBean.get(i).child.get(c).name;
                childBean.id = jsonBean.get(i).child.get(c).id;
                CityList.add(childBean);//添加城市
                ArrayList<JsonNewBean.ChildBeanX.ChildBean> City_AreaList = new ArrayList<>();//该城市的所有地区列表
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).child.get(c).name == null
                        || jsonBean.get(i).child.get(c).child.size() == 0) {
                    City_AreaList.add(new JsonNewBean.ChildBeanX.ChildBean());
                } else {

                    for (int d = 0; d < jsonBean.get(i).child.get(c).child.size(); d++) {//该城市对应地区所有数据
                        JsonNewBean.ChildBeanX.ChildBean childBean1 = new JsonNewBean.ChildBeanX.ChildBean();
                        childBean1.name = jsonBean.get(i).child.get(c).child.get(d).name;
                        childBean1.id = jsonBean.get(i).child.get(c).child.get(d).id;
                        City_AreaList.add(childBean1);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityList);
            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    private void takePicture() {
        DialogUtils.createPopwindow(this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH);
                Uri data;
                // 判断版本大于等于7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    // "net.csdn.blog.ruancoder.fileprovider"即是在清单文件中配置的authorities
                    data = FileProvider.getUriForFile(UploadABusinessCardActivity.this, "com.braveman.im.fileprovider", file);
                    // 给目标应用一个临时授权
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    data = Uri.fromFile(file);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT, data);
                UploadABusinessCardActivity.this.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);


            }
        }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
            @Override
            public void onClick(CustomPopwindow popwindow, View view) {

                Intent i = new Intent(
                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, REQUEST_CAMERA_CODE);
            }
        }).showAtLocation(mTitleBarView, Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 0, 130);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture();
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
            case MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takePicture();
                } else {
                    Toast.makeText(this, "请打开拍照权限", Toast.LENGTH_SHORT).show();
                }
                break;
        }

        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {

                case REQUEST_CODE_TAKE_PHOTO:
                    String filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH;
                    new CompressPhotoThread(mHandler, filePath, 0).start();
                    break;
                //                 选择照片
                case REQUEST_CAMERA_CODE:
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = this.getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    new CompressPhotoThread(mHandler, picturePath, 1).start();
                    break;
            }
        }
    }
}
